package com.weixin.paleituo.view;

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.weixin.paleituo.R;
import com.weixin.paleituo.activity.NewShippingAddressActivity;
import com.weixin.paleituo.annotation.RankAreaType;
import com.weixin.paleituo.bean.AreaInfoBean;
import com.weixin.paleituo.fragment.ShippingAreaFragment;
import com.weixin.paleituo.util.UIUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 区域选择弹框
 *
 * @author fengzhen
 * @version v1.0, 2018/3/30
 */
public class AreaSelectorDialogFragment extends DialogFragment implements DialogInterface.OnKeyListener, ShippingAreaFragment.OnAreaChooseListner, RadioGroup.OnCheckedChangeListener {

    public static final String ARGS_AREALIST = "args_arealist";
    public static final String ARGS_PROVINCE = "args_province";
    public static final String ARGS_CITY = "args_city";
    public static final String ARGS_DISTRICT = "args_district";

    @BindView(R.id.group_rank_content_pop_window_area_selector)
    RadioGroup mGroupRankContent;
    @BindView(R.id.view_pager_pop_window_area_selector)
    ForbidScrollViewpager mViewPagerPopWindowAreaSelector;
    @BindView(R.id.rbtn_provice_pop_window_area_selector)
    RadioButton mRbtnProvicePopWindowAreaSelector;
    @BindView(R.id.rbtn_city_pop_window_area_selector)
    RadioButton mRbtnCityPopWindowAreaSelector;
    @BindView(R.id.rbtn_district_pop_window_area_selector)
    RadioButton mRbtnDistrictPopWindowAreaSelector;

    private ArrayList<AreaInfoBean> mAddressList = new ArrayList<>();
    private AreaPagerAdapter mAreaPagerAdapter;

    // 默认选择省 默认等级为Province
    @RankAreaType
    private int mCurrentRank = RankAreaType.AREA_PROVINCE;
    private List<String> mRanksContent = new ArrayList<>();

    private boolean isUpdate = false;

    private AreaInfoBean mProvince;
    private AreaInfoBean mCity;
    private AreaInfoBean mDistrict;

    /**
     * 创建弹框
     */
    public static AreaSelectorDialogFragment newInstance(ArrayList<AreaInfoBean> areaList) {
        Bundle args = new Bundle();
        args.putSerializable(ARGS_AREALIST, areaList);
        AreaSelectorDialogFragment fragment = new AreaSelectorDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 创建弹框
     */
    public static AreaSelectorDialogFragment newInstance(
            ArrayList<AreaInfoBean> areaList, AreaInfoBean province, AreaInfoBean city, AreaInfoBean district) {
        Bundle args = new Bundle();
        args.putSerializable(ARGS_AREALIST, areaList);
        args.putParcelable(ARGS_PROVINCE, province);
        args.putParcelable(ARGS_CITY, city);
        args.putParcelable(ARGS_DISTRICT, district);
        AreaSelectorDialogFragment fragment = new AreaSelectorDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onStart() {
        super.onStart();
        initDialog();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.areaDialogFragmentStyle);

        Bundle arguments = getArguments();
        mAddressList.addAll((ArrayList<AreaInfoBean>) arguments.getSerializable(ARGS_AREALIST));
        mProvince = arguments.getParcelable(ARGS_PROVINCE);
        mCity = arguments.getParcelable(ARGS_CITY);
        mDistrict = arguments.getParcelable(ARGS_DISTRICT);
        if (mProvince != null && mCity != null && mDistrict != null) {
            isUpdate = true;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View inflate = inflater.inflate(R.layout.pop_window_area_selector, container);
        ButterKnife.bind(this, inflate);
        this.setCancelable(false);

        initDefaultUI();

        return inflate;
    }

    /**
     * 设置默认UI样式
     *
     * @author fengzhen
     * @version v1.0, 2018/3/31
     */
    private void initDefaultUI() {
        Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.bottom_line_greeen);
        if (isUpdate) {
            mRanksContent.add(mProvince.getName());
            mRanksContent.add(mCity.getName());
            mRanksContent.add(mDistrict.getName());
            refreshRadioGroup();
//            mRbtnProvicePopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
//            mRbtnCityPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
//            mRbtnDistrictPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawable);
        } else {
            mRanksContent.add("请选择");
            refreshRadioGroup();
            // 代码设置默认选中下划线位置
//            mRbtnProvicePopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawable);
//            mRbtnCityPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
//            mRbtnDistrictPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
        // 展示区域选择
        mAreaPagerAdapter = new AreaPagerAdapter(getChildFragmentManager(), this);
        mViewPagerPopWindowAreaSelector.setAdapter(mAreaPagerAdapter);
        mGroupRankContent.setOnCheckedChangeListener(this);
        // 如果是更新区域，默认选中最后一个Fragment
        if (isUpdate) {
            mViewPagerPopWindowAreaSelector.setCurrentItem(mRanksContent.size() - 1);
        }
    }

    /**
     * 对DialogFragment进行初始化操作，铺满全屏，
     * 使之类似PopupWindow的展示效果
     *
     * @author fengzhen
     * @version v1.0, 2018/3/30
     */
    private void initDialog() {
        Window win = getDialog().getWindow();
        // 一定要设置Background，如果不设置，window属性设置无效
        win.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.c_99000000)));
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams params = win.getAttributes();
        params.dimAmount = 0.0f;
        params.gravity = Gravity.BOTTOM;
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        win.setAttributes(params);
    }

    /**
     * Tab点击事件逻辑处理
     * 选中对应Fragment 同时刷新Radiobutton的绿色下划线
     *
     * @author fengzhen
     * @version v1.0, 2018/3/30
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rbtn_provice_pop_window_area_selector:
                mViewPagerPopWindowAreaSelector.setCurrentItem(0);
                Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.bottom_line_greeen);
                drawable.setBounds(0, 0, mRbtnProvicePopWindowAreaSelector.getWidth(), UIUtils.dip2px(2));
                mRbtnProvicePopWindowAreaSelector.setCompoundDrawables(null, null, null, drawable);
//                mRbtnProvicePopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, ContextCompat.getDrawable(getContext(), R.drawable.bottom_line_greeen));
                mRbtnCityPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                mRbtnDistrictPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                break;
            case R.id.rbtn_city_pop_window_area_selector:
                mViewPagerPopWindowAreaSelector.setCurrentItem(1);
                Drawable drawable1 = ContextCompat.getDrawable(getContext(), R.drawable.bottom_line_greeen);
                drawable1.setBounds(0, 0, mRbtnCityPopWindowAreaSelector.getWidth(), UIUtils.dip2px(2));
                mRbtnCityPopWindowAreaSelector.setCompoundDrawables(null, null, null, drawable1);
                mRbtnProvicePopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
//                mRbtnCityPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, ContextCompat.getDrawable(getContext(), R.drawable.bottom_line_greeen));
                mRbtnDistrictPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                break;
            case R.id.rbtn_district_pop_window_area_selector:
                mViewPagerPopWindowAreaSelector.setCurrentItem(2);
                Drawable drawable2 = ContextCompat.getDrawable(getContext(), R.drawable.bottom_line_greeen);
                drawable2.setBounds(0, 0, mRbtnDistrictPopWindowAreaSelector.getWidth(), UIUtils.dip2px(2));
                mRbtnDistrictPopWindowAreaSelector.setCompoundDrawables(null, null, null, drawable2);
                mRbtnProvicePopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                mRbtnCityPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
//                mRbtnDistrictPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, ContextCompat.getDrawable(getContext(), R.drawable.bottom_line_greeen));
                break;
        }
    }

    /**
     * 区域选择事件监听处理
     *
     * @author fengzhen
     * @version v1.0, 2018/3/30
     */
    @Override
    public void onAreaChoose(int rank, AreaInfoBean area, List<AreaInfoBean> nextArea) {
        mCurrentRank = rank + 1;
        switch (mCurrentRank) {
            case RankAreaType.AREA_CITY: {
                mRanksContent.clear();
                mProvince = area;
                mCity = null;
                mDistrict = null;
                mRanksContent.add(area.getName());
                mRanksContent.add("请选择");
                turn2Next();

                List<Map<Integer, ShippingAreaFragment>> maps = mAreaPagerAdapter.getmFragments();
                for (Map<Integer, ShippingAreaFragment> map :
                        maps) {
                    ShippingAreaFragment shippingAreaFragment = map.get(RankAreaType.AREA_CITY);
                    if (shippingAreaFragment != null) {
                        shippingAreaFragment.setArea(getRankList(RankAreaType.AREA_CITY));
                    }
                }
                break;
            }
            case RankAreaType.AREA_DISTRICT: {
                mRanksContent.clear();
                mCity = area;
                mDistrict = null;
                mRanksContent.add(mProvince.getName());
                mRanksContent.add(area.getName());
                mRanksContent.add("请选择");
                turn2Next();

                List<Map<Integer, ShippingAreaFragment>> maps = mAreaPagerAdapter.getmFragments();
                for (Map<Integer, ShippingAreaFragment> map :
                        maps) {
                    ShippingAreaFragment shippingAreaFragment = map.get(RankAreaType.AREA_DISTRICT);
                    if (shippingAreaFragment != null) {
                        shippingAreaFragment.setArea(getRankList(RankAreaType.AREA_DISTRICT));
                    }
                }
                break;
            }
            case RankAreaType.AREA_FINISH: {
                mDistrict = area;
                mRanksContent.add(mProvince.getName());
                mRanksContent.add(area.getName());
                mRanksContent.add(mDistrict.getName());
                mCurrentRank--;
                // 返回数据
                FragmentActivity activity = getActivity();
                if (activity instanceof NewShippingAddressActivity) {
                    ((NewShippingAddressActivity) activity).setArea(
                            mProvince,
                            mCity,
                            mDistrict);
                }
                dismiss();
                break;
            }
        }
    }

    /**
     * 跳转下一页
     *
     * @author fengzhen
     * @version v1.0, 2018/3/30
     */
    private void turn2Next() {
        mAreaPagerAdapter.notifyDataSetChanged();
        refreshRadioGroup();
    }

    /**
     * 刷新区域Tab信息
     *
     * @author fengzhen
     * @version v1.0, 2018/3/30
     */
    private void refreshRadioGroup() {
        mRbtnProvicePopWindowAreaSelector.setText(mRanksContent.get(0));
        if (mRanksContent.size() > 1) {
            mRbtnCityPopWindowAreaSelector.setVisibility(View.VISIBLE);
            mRbtnCityPopWindowAreaSelector.setText(mRanksContent.get(1));
        } else {
            mRbtnCityPopWindowAreaSelector.setVisibility(View.GONE);
        }
        if (mRanksContent.size() > 2) {
            mRbtnDistrictPopWindowAreaSelector.setText(mRanksContent.get(2));
            mRbtnDistrictPopWindowAreaSelector.setVisibility(View.VISIBLE);
        } else {
            mRbtnDistrictPopWindowAreaSelector.setVisibility(View.GONE);
        }
        Runnable action = new Runnable() {
            @Override
            public void run() {
                if (mRanksContent.size() == 1) {
                    Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.bottom_line_greeen);
                    TextPaint paint = mRbtnProvicePopWindowAreaSelector.getPaint();
                    int textSize = (int) paint.measureText(mRbtnProvicePopWindowAreaSelector.getText().toString());
                    drawable.setBounds(0, 0, textSize, UIUtils.dip2px(2));
                    mRbtnProvicePopWindowAreaSelector.setCompoundDrawables(null, null, null, drawable);
                } else {
                    mRbtnProvicePopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                }
                if (mRanksContent.size() == 2) {
                    Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.bottom_line_greeen);
                    TextPaint paint = mRbtnCityPopWindowAreaSelector.getPaint();
                    int textSize = (int) paint.measureText(mRbtnCityPopWindowAreaSelector.getText().toString());
                    drawable.setBounds(0, 0, textSize, UIUtils.dip2px(2));
                    mRbtnCityPopWindowAreaSelector.setCompoundDrawables(null, null, null, drawable);
                } else {
                    mRbtnCityPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                }
                if (mRanksContent.size() == 3) {
                    Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.bottom_line_greeen);
                    TextPaint paint = mRbtnDistrictPopWindowAreaSelector.getPaint();
                    int textSize = (int) paint.measureText(mRbtnDistrictPopWindowAreaSelector.getText().toString());
                    drawable.setBounds(0, 0, textSize, UIUtils.dip2px(2));
                    mRbtnDistrictPopWindowAreaSelector.setCompoundDrawables(null, null, null, drawable);
                } else {
                    mRbtnDistrictPopWindowAreaSelector.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                }
            }
        };
        mRbtnProvicePopWindowAreaSelector.post(action);
        mRbtnCityPopWindowAreaSelector.post(action);
        mRbtnDistrictPopWindowAreaSelector.post(action);
        ((RadioButton) mGroupRankContent.getChildAt(mRanksContent.size() - 1)).setChecked(true);
    }

    /**
     * 点击物理返回键是否消失，默认消失
     *
     * @author fengzhen
     * @version v1.0, 2017/6/21 14:34
     */
    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 使用反射重写showAllowingStateLoss()方法
     * 解决调用show()方法异常
     *
     * @author fengzhen
     * @version v1.0, 2017/7/2 17:29
     */
    public void showAllowingStateLoss(FragmentManager manager, String tag) {
        try {
            Field mDismissed = DialogFragment.class.getDeclaredField("mDismissed");
            mDismissed.setAccessible(true);
            mDismissed.set(this, false);
            Field mShownByMe = DialogFragment.class.getDeclaredField("mShownByMe");
            mShownByMe.setAccessible(true);
            mShownByMe.set(this, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    }

    @OnClick({R.id.frame_close, R.id.frame_background_pop_window_area_selector})
    public void onClick() {
        this.dismiss();
    }

    /**
     * 区域列表选择Adapter
     *
     * @author fengzhen
     * @version v1.0, 2018/3/30
     */
    public class AreaPagerAdapter extends FragmentPagerAdapter {

        private ShippingAreaFragment.OnAreaChooseListner listner;
        private List<Map<Integer, ShippingAreaFragment>> mFragments = new ArrayList<>();

        public List<Map<Integer, ShippingAreaFragment>> getmFragments() {
            return mFragments;
        }

        public AreaPagerAdapter(FragmentManager fm, ShippingAreaFragment.OnAreaChooseListner listner) {
            super(fm);
            this.listner = listner;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return mRanksContent.get(position);
        }

        @Override
        public Fragment getItem(int position) {
            int rank = -1;
            switch (position) {
                case 0:
                    rank = RankAreaType.AREA_PROVINCE;
                    break;
                case 1:
                    rank = RankAreaType.AREA_CITY;
                    break;
                case 2:
                    rank = RankAreaType.AREA_DISTRICT;
                    break;
            }
            ShippingAreaFragment fragment = ShippingAreaFragment.newInstance(getRankList(rank), rank, getRankArea(rank));
            fragment.setOnAreaChooseListenre(listner);

            // 保存Fragment
            HashMap<Integer, ShippingAreaFragment> e = new HashMap<>();
            e.put(rank, fragment);
            mFragments.add(e);

            return fragment;
        }

        @Override
        public int getCount() {
            return mRanksContent.size();
        }

    }

    /**
     * 根据行政区等级，获取当前选中的行政区Bean
     *
     * @param rank 行政区等级
     * @author fengzhen
     * @version v1.0, 2018/3/30
     */
    private AreaInfoBean getRankArea(int rank) {
        switch (rank) {
            case RankAreaType.AREA_PROVINCE:
                return mProvince;
            case RankAreaType.AREA_CITY:
                return mCity;
            case RankAreaType.AREA_DISTRICT:
                return mDistrict;
            default:
                return null;
        }
    }

    /**
     * 根据对应行政区等级，以及当前行政区，获取下级地区列表
     *
     * @param rank 行政区等级 3级划分
     * @author fengzhen
     * @version v1.0, 2018/3/30
     */
    private ArrayList<AreaInfoBean> getRankList(int rank) {
        switch (rank) {
            case RankAreaType.AREA_PROVINCE: {
                return mAddressList;
            }
            case RankAreaType.AREA_CITY: {
                for (AreaInfoBean areaCity :
                        mAddressList) {
                    if (mProvince.getId() == areaCity.getId()) {
                        return (ArrayList<AreaInfoBean>) areaCity.getChildren();
                    }
                }
                break;
            }
            case RankAreaType.AREA_DISTRICT: {
                for (AreaInfoBean areaCity :
                        mAddressList) {
                    if (mProvince.getId() == areaCity.getId()) {
                        for (AreaInfoBean areaDistrict :
                                areaCity.getChildren()) {
                            if (mCity.getId() == areaDistrict.getId()) {
                                return (ArrayList<AreaInfoBean>) areaDistrict.getChildren();
                            }
                        }
                    }
                }
                break;
            }
        }
        return null;
    }
}
